package org.ktjy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.ktjy.demoLian.entity.SysRight;
import org.ktjy.demoLian.entity.SysRoleRight;
import org.ktjy.demoLian.entity.SysUser;
import org.ktjy.demoLian.entity.vo.SysUserVo;
import org.ktjy.demoLian.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping
public class SysUserControllerLogin {

    @Autowired
    ISysUserService sysUserService;

    @RequestMapping("/")
    public String getlogin() {
        return "login";
    }

    @RequestMapping("doLogin")
    public String getdoLogin(String usrName, String usrPassword, Model model, HttpSession session) {

        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);

            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            SysUserVo sysUser = (SysUserVo) subject.getPrincipal();
            int rid = Math.toIntExact(sysUser.getUsrRoleId());
            System.out.println(rid);

            List<SysRight> lsit = sysUserService.getRights(rid);
            sysUser.getRole().setRights(lsit);
            session.setAttribute("loginUser", sysUser);
            model.addAttribute("loginUser", sysUser);
            return "main";
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "账号不存在");
            return "login";
        } catch (LockedAccountException e) {
            System.out.println("令牌过期");
            model.addAttribute("message", "账号或密码错误");
            return "login";
        } catch (AuthenticationException e) {
            System.out.println("令牌错误");
            model.addAttribute("message", "令牌错误");
            return "login";
        }
    }

}
